<template>
  <el-dialog
    :title="isEdit ? '编辑模板' : '新增模板'"
    v-model="dialogVisible"
    width="650px"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    @closed="handleClosed"
    custom-class="datav-dialog"
    :modal-class="'datav-modal'"
  >
    <dv-decoration-8 class="dialog-header-decoration" :reverse="true" />
    <dv-border-box-8 class="datav-form-container" :dur="5">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        label-position="right"
        class="template-form"
      >
      <!-- 标题 -->
      <el-form-item label="模板标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入模板标题" maxlength="50" show-word-limit class="datav-input" />
      </el-form-item>

      <!-- 标签 -->
      <el-form-item label="标签" prop="tags">
        <el-tag
          v-for="tag in dynamicTags"
          :key="tag"
          class="mx-1 datav-tag"
          closable
          :disable-transitions="false"
          @close="handleTagClose(tag)"
        >
          {{ tag }}
        </el-tag>
        <el-input
          v-if="inputVisible"
          ref="tagInputRef"
          v-model="inputValue"
          class="ml-1 w-20 datav-input"
          size="small"
          @keyup.enter="handleTagInputConfirm"
          @blur="handleTagInputConfirm"
        />
        <el-button v-else class="button-new-tag ml-1" size="small" @click="showTagInput">
          + 添加标签
        </el-button>
      </el-form-item>

      <!-- 预览图 -->
      <el-form-item label="预览图" prop="imgPreview">
        <div class="preview-container">
          <el-upload
            class="template-image-uploader"
            action="#"
            :http-request="uploadImage"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
            accept="image/*"
          >
            <img v-if="form.imgPreview" :src="form.imgPreview" class="template-image" />
            <div v-else class="template-image-uploader-icon">
              <el-icon><Plus /></el-icon>
              <div class="upload-text">支持jpg、png格式</div>
            </div>
          </el-upload>
          <div class="upload-tip">建议尺寸750x450px</div>
        </div>
      </el-form-item>

      <!-- Word文档 -->
      <el-form-item label="Word文档" prop="fileId">
        <div class="file-upload-container">
          <el-upload
            class="template-file-uploader"
            action="#"
            :http-request="uploadWord"
            :show-file-list="false"
            :before-upload="beforeWordUpload"
            accept=".doc,.docx"
          >
            <el-button type="primary" class="tech-button tech-button--primary" :loading="wordUploading">
              <el-icon><Upload /></el-icon>
              {{ form.fileId ? '重新上传Word' : '上传Word文档' }}
            </el-button>
          </el-upload>
          <div v-if="form.fileId" class="file-uploaded">
            <el-icon><Document /></el-icon>
            <span>已上传Word文档</span>
          </div>
        </div>
      </el-form-item>

      <!-- PDF文档 -->
      <el-form-item label="PDF文档" prop="fileIdPdf">
        <div class="file-upload-container">
          <el-upload
            class="template-file-uploader"
            action="#"
            :http-request="uploadPdf"
            :show-file-list="false"
            :before-upload="beforePdfUpload"
            accept=".pdf"
          >
            <el-button type="primary" class="tech-button tech-button--primary" :loading="pdfUploading">
              <el-icon><Upload /></el-icon>
              {{ form.fileIdPdf ? '重新上传PDF' : '上传PDF文档' }}
            </el-button>
          </el-upload>
          <div v-if="form.fileIdPdf" class="file-uploaded">
            <el-icon><Document /></el-icon>
            <span>已上传PDF文档</span>
          </div>
        </div>
      </el-form-item>

      <!-- 启用状态 -->
      <el-form-item label="启用状态" prop="enable">
        <div class="switch-container">
          <el-switch
            v-model="form.enable"
            active-text="启用"
            inactive-text="禁用"
            :active-value="true"
            :inactive-value="false"
            class="datav-switch"
          />
          <span class="status-text">当前状态：{{ form.enable ? '启用' : '禁用' }}</span>
        </div>
      </el-form-item>
    </el-form>
    </dv-border-box-8>

    <template #footer>
      <dv-border-box-1 class="datav-dialog-footer-box">
        <div class="datav-dialog-footer">
          <el-button class="tech-button" @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" class="tech-button tech-button--primary" @click="submitForm" :loading="submitting">保存</el-button>
        </div>
      </dv-border-box-1>
    </template>
    <dv-decoration-8 class="dialog-footer-decoration" />
  </el-dialog>
</template>

<script>
import { ref, reactive, computed, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Upload, Document } from '@element-plus/icons-vue'
import { app } from '../../utils/cloudbase'
import dayjs from 'dayjs'
import { v4 as uuidv4 } from 'uuid'

export default {
  name: 'TemplateFormDialog',
  components: {
    Plus,
    Upload,
    Document
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    templateData: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['update:visible', 'submit-success'],
  setup(props, { emit }) {
    // 表单引用
    const formRef = ref(null)
    
    // 对话框可见性
    const dialogVisible = computed({
      get: () => props.visible,
      set: (val) => emit('update:visible', val)
    })

    // 判断是否为编辑模式
    const isEdit = computed(() => !!props.templateData._id || !!props.templateData.id)

    // 表单数据
    const form = reactive({
      id: uuidv4(), // 使用 uuid 生成随机 ID
      _id: '', // 添加 _id 字段用于更新操作
      title: '',
      tags: '',
      imgPreview: '',
      imgFileId: "",
      enable: true,
      fileId: '',
      fileIdPdf: ''
    })

    // 标签相关
    const dynamicTags = ref([])
    const inputVisible = ref(false)
    const inputValue = ref('')
    const tagInputRef = ref(null)

    // 上传状态
    const wordUploading = ref(false)
    const pdfUploading = ref(false)
    const submitting = ref(false)

    // 表单验证规则
    const rules = reactive({
      title: [
        { required: true, message: '请输入模板标题', trigger: 'blur' },
        { min: 1, max: 50, message: '标题长度应为1-50个字符', trigger: 'blur' }
      ],
      tags: [
        { required: true, message: '请至少添加一个标签', trigger: 'change' }
      ],
      imgPreview: [
        { required: true, message: '请上传预览图', trigger: 'change' }
      ],
      fileId: [
        { 
          validator: (rule, value, callback) => {
            if (!value && !form.fileIdPdf) {
              callback(new Error('请至少上传一种格式的文档(Word或PDF)'))
            } else {
              callback()
            }
          }, 
          trigger: 'change' 
        }
      ]
    })

    // 监听模板数据变化，填充表单
    watch(() => props.templateData, (newVal) => {
      if (newVal && Object.keys(newVal).length > 0) {
        // 填充表单数据
        Object.keys(form).forEach(key => {
          if (newVal[key] !== undefined) {
            form[key] = newVal[key]
          }
        })
        
        // 特别处理 _id 字段
        if (newVal._id) {
          form._id = newVal._id
        }
        
        // 处理标签
        if (newVal.tags) {
          dynamicTags.value = newVal.tags.split(',').filter(tag => tag.trim() !== '')
        } else {
          dynamicTags.value = []
        }
      }
    }, { immediate: true, deep: true })

    // 标签相关方法
    const showTagInput = () => {
      inputVisible.value = true
      nextTick(() => {
        tagInputRef.value.focus()
      })
    }

    const handleTagClose = (tag) => {
      dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
      form.tags = dynamicTags.value.join(',')
    }

    const handleTagInputConfirm = () => {
      if (inputValue.value) {
        if (!dynamicTags.value.includes(inputValue.value)) {
          dynamicTags.value.push(inputValue.value)
          form.tags = dynamicTags.value.join(',')
        }
      }
      inputVisible.value = false
      inputValue.value = ''
    }

    // 图片上传前验证
    const beforeImageUpload = (file) => {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        ElMessage.error('上传文件只能是图片格式!')
        return false
      }
      if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过 2MB!')
        return false
      }
      return true
    }

    // Word文档上传前验证
    const beforeWordUpload = (file) => {
      const isWord = file.name.endsWith('.doc') || file.name.endsWith('.docx')
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isWord) {
        ElMessage.error('只能上传Word文档(.doc/.docx)!')
        return false
      }
      if (!isLt10M) {
        ElMessage.error('上传文件大小不能超过 10MB!')
        return false
      }
      return true
    }

    // PDF文档上传前验证
    const beforePdfUpload = (file) => {
      const isPdf = file.name.endsWith('.pdf')
      const isLt10M = file.size / 1024 / 1024 < 3

      if (!isPdf) {
        ElMessage.error('只能上传PDF文档(.pdf)!')
        return false
      }
      if (!isLt10M) {
        ElMessage.error('上传文件大小不能超过 3MB!')
        return false
      }
      return true
    }

    // 生成存储路径
    const generatePath = (prefix) => {
      const date = dayjs().format('YYYYMMDD')
      const time = dayjs().format('HHmmss')
      return `${prefix}/${date}/${time}`
    }

    // 上传图片
    const uploadImage = async (options) => {
      try {
        const file = options.file
        // 转换为Base64
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = async (e) => {
          const base64Content = e.target.result.split(',')[1]
          
          try {
            const result = await app.callFunction({
              name: 'admin-file-upload',
              data: {
                fileContent: base64Content,
                fileName: file.name,
                folder: generatePath('image')
              }
            })
            
            if (result.result.code === 0) {
              form.imgPreview = result.result.data.fileUrl
              form.imgFileId = result.result.data.fileId
              ElMessage.success('图片上传成功')
            } else {
              ElMessage.error(result.result.message || '图片上传失败')
            }
          } catch (error) {
            console.error('图片上传失败:', error)
            ElMessage.error('图片上传失败')
          }
        }
      } catch (error) {
        console.error('图片读取失败:', error)
        ElMessage.error('图片读取失败')
      }
    }

    // 上传Word文档
    const uploadWord = async (options) => {
      try {
        wordUploading.value = true
        const file = options.file
        // 转换为Base64
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = async (e) => {
          const base64Content = e.target.result.split(',')[1]
          
          try {
            const result = await app.callFunction({
              name: 'admin-file-upload',
              data: {
                fileContent: base64Content,
                fileName: file.name,
                folder: generatePath('resumeAuto')
              }
            })
            
            if (result.result.code === 0) {
              form.fileId = result.result.data.fileId
              ElMessage.success('Word文档上传成功')
            } else {
              ElMessage.error(result.result.message || 'Word文档上传失败')
            }
          } catch (error) {
            console.error('Word文档上传失败:', error)
            ElMessage.error('Word文档上传失败')
          } finally {
            wordUploading.value = false
          }
        }
      } catch (error) {
        console.error('Word文档读取失败:', error)
        ElMessage.error('Word文档读取失败')
        wordUploading.value = false
      }
    }

    // 上传PDF文档
    const uploadPdf = async (options) => {
      try {
        pdfUploading.value = true
        const file = options.file
        // 转换为Base64
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = async (e) => {
          const base64Content = e.target.result.split(',')[1]
          
          try {
            const result = await app.callFunction({
              name: 'admin-file-upload',
              data: {
                fileContent: base64Content,
                fileName: file.name,
                folder: generatePath('resumeAuto')
              }
            })
            
            if (result.result.code === 0) {
              form.fileIdPdf = result.result.data.fileId
              ElMessage.success('PDF文档上传成功')
            } else {
              ElMessage.error(result.result.message || 'PDF文档上传失败')
            }
          } catch (error) {
            console.error('PDF文档上传失败:', error)
            ElMessage.error('PDF文档上传失败')
          } finally {
            pdfUploading.value = false
          }
        }
      } catch (error) {
        console.error('PDF文档读取失败:', error)
        ElMessage.error('PDF文档读取失败')
        pdfUploading.value = false
      }
    }

    // 提交表单
    const submitForm = async () => {
      if (!formRef.value) return
      
      await formRef.value.validate(async (valid) => {
        if (valid) {
          // 确保标签已更新到表单
          form.tags = dynamicTags.value.join(',')
          
          // 验证是否至少上传了一种文档
          if (!form.fileId && !form.fileIdPdf) {
            ElMessage.error('请至少上传一种格式的文档(Word或PDF)')
            return
          }
          
          submitting.value = true
          try {
            const action = isEdit.value ? 'update' : 'create'
            
            // 准备提交的数据
            const formData = { ...form }
            
            // 如果是编辑模式，确保使用 _id 作为唯一标识
            // 注意：id 和 _id 是独立的字段，删除和更新操作都需要通过 _id 来进行查询
            if (isEdit.value) {
              formData._id = formData._id
            }else {
              // 删除 formData 中的 _id 字段
              delete formData._id
            }
            
            const result = await app.callFunction({
              name: 'admin-resume-templates-crud',
              data: {
                action,
                data: formData
              }
            })
            
            if (result.result.code === 0) {
              ElMessage.success(isEdit.value ? '模板更新成功' : '模板创建成功')
              dialogVisible.value = false
              emit('submit-success')
            } else {
              ElMessage.error(result.result.message || (isEdit.value ? '模板更新失败' : '模板创建失败'))
            }
          } catch (error) {
            console.error(isEdit.value ? '更新模板失败:' : '创建模板失败:', error)
            ElMessage.error(isEdit.value ? '更新模板失败' : '创建模板失败')
          } finally {
            submitting.value = false
          }
        } else {
          ElMessage.warning('请完善表单信息')
          return false
        }
      })
    }

    // 对话框关闭时重置表单
    const handleClosed = () => {
      formRef.value?.resetFields()
      Object.keys(form).forEach(key => {
        if (key === 'enable') {
          form[key] = true
        } else if (key === 'id') {
          form[key] = uuidv4() // 生成新的 uuid
        } else {
          form[key] = ''
        }
      })
      dynamicTags.value = []
      inputVisible.value = false
      inputValue.value = ''
    }

    return {
      dialogVisible,
      isEdit,
      form,
      formRef,
      rules,
      dynamicTags,
      inputVisible,
      inputValue,
      tagInputRef,
      wordUploading,
      pdfUploading,
      submitting,
      showTagInput,
      handleTagClose,
      handleTagInputConfirm,
      beforeImageUpload,
      beforeWordUpload,
      beforePdfUpload,
      uploadImage,
      uploadWord,
      uploadPdf,
      submitForm,
      handleClosed
    }
  }
}
</script>
<style>
 .el-dialog {
  background-color: rgba(0, 19, 47, 0.9) !important;
  border: 1px solid rgba(0, 192, 255, 0.5) !important;
  box-shadow: 0 0 15px rgba(0, 192, 255, 0.3) !important;
  border-radius: 4px !important;
  backdrop-filter: blur(5px);
  background: rgba(0, 19, 47) !important;
  overflow: hidden !important;
}
.el-dialog__title {
  color: #00c0ff !important;
  font-weight: bold !important;
}
.el-input__count-inner{
  background: inherit !important;
}
</style>
<style scoped>
.template-form {
  max-height: 60vh;
  overflow-y: auto;
  padding: 20px;
  color: #00c0ff;
}

.datav-form-container {
  width: 100%;
  height: auto;
  padding: 10px;
  background-color: rgba(0, 19, 47, 0.8);
}

:deep(.dv-border-box-8) {
  --dv-bb8-color: rgba(0, 192, 255, 0.6);
}

.datav-dialog-footer-box {
  width: 100%;
  height: 50px;
}

.datav-dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

:deep(.datav-dialog) {
  background-color: rgba(0, 19, 47, 0.9) !important;
  border: 1px solid rgba(0, 192, 255, 0.5) !important;
  box-shadow: 0 0 15px rgba(0, 192, 255, 0.3) !important;
  border-radius: 4px !important;
  backdrop-filter: blur(5px);
    background: rgba(0, 19, 47) !important;
    overflow: hidden !important;
}

:deep(.datav-dialog .el-dialog) {
  background-color: rgba(0, 19, 47, 0.9) !important;
  border: 1px solid rgba(0, 192, 255, 0.5) !important;
  box-shadow: 0 0 15px rgba(0, 192, 255, 0.3) !important;
}

:deep(.datav-dialog .el-dialog__header) {
  background-color: rgba(0, 30, 60, 0.8) !important;
  border-bottom: 1px solid rgba(0, 192, 255, 0.3) !important;
  padding: 15px 20px !important;
  position: relative;
}

.dialog-header-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 30px;
  z-index: 1;
}

.dialog-footer-decoration {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 30px;
  z-index: 1;
}



:deep(.datav-dialog .el-dialog__headerbtn .el-dialog__close) {
  color: #00c0ff !important;
}

:deep(.datav-dialog .el-dialog__body) {
  background-color: rgba(0, 19, 47, 0.8) !important;
  padding: 20px !important;
  color: #00c0ff !important;
}

:deep(.datav-dialog .el-dialog__footer) {
  background-color: rgba(0, 30, 60, 0.8) !important;
  border-top: 1px solid rgba(0, 192, 255, 0.3) !important;
  padding: 10px 20px !important;
  height: 70px;
}

:deep(.el-overlay) {
  background-color: rgba(0, 10, 30, 0.7) !important;
  backdrop-filter: blur(3px);
}

:deep(.dv-border-box-1) {
  --dv-bb1-color: rgba(0, 192, 255, 0.5);
}

:deep(.el-form-item__label) {
  color: #00c0ff !important;
}

:deep(.el-input__wrapper) {
  background-color: rgba(0, 30, 60, 0.6) !important;
  border: 1px solid rgba(0, 192, 255, 0.5) !important;
  box-shadow: none !important;
}

:deep(.el-input__inner) {
  color: #ffffff !important;
}

:deep(.el-switch__core) {
  border-color: rgba(0, 192, 255, 0.5) !important;
  background-color: rgba(0, 30, 60, 0.6) !important;
}

:deep(.el-switch.is-checked .el-switch__core) {
  background-color: #00c0ff !important;
}

.template-image-uploader {
  display: flex;
  flex-direction: column;
}

.template-image-uploader .el-upload {
  border: 1px dashed rgba(0, 192, 255, 0.5);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  background-color: rgba(0, 30, 60, 0.4);
}

.template-image-uploader .el-upload:hover {
  border-color: #00c0ff;
  box-shadow: 0 0 10px rgba(0, 192, 255, 0.3);
}

.template-image-uploader-icon {
  font-size: 28px;
  color: #00c0ff;
  width: 178px;
  height: 178px;
  text-align: center;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 30, 60, 0.4);
  border: 1px dashed rgba(0, 192, 255, 0.5);
  border-radius: 4px;
}

.upload-text {
  font-size: 14px;
  margin-top: 10px;
}

.preview-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.file-upload-container {
  display: flex;
  align-items: center;
}

.switch-container {
  display: flex;
  align-items: center;
}

.status-text {
  margin-left: 10px;
  color: #00c0ff;
}

.template-image {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
  border: 2px solid rgba(0, 192, 255, 0.7);
  border-radius: 4px;
  box-shadow: 0 0 10px rgba(0, 192, 255, 0.3);
}

.upload-tip {
  font-size: 12px;
  color: rgba(0, 192, 255, 0.7);
  margin-top: 5px;
}

.template-file-uploader {
  display: flex;
  align-items: center;
}

.file-uploaded {
  display: flex;
  align-items: center;
  margin-left: 10px;
  color: #00c0ff;
}

.file-uploaded .el-icon {
  margin-right: 5px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
  background-color: rgba(0, 30, 60, 0.6) !important;
  border: 1px solid rgba(0, 192, 255, 0.5) !important;
  color: #00c0ff !important;
}

.button-new-tag:hover {
  background-color: rgba(0, 30, 60, 0.8) !important;
  border-color: #00c0ff !important;
  color: #ffffff !important;
}

:deep(.el-tag) {
  background-color: rgba(0, 30, 60, 0.6) !important;
  border-color: rgba(0, 192, 255, 0.5) !important;
  color: #ffffff !important;
}

:deep(.datav-tag) {
  margin-bottom: 5px;
}

:deep(.datav-input .el-input__wrapper) {
  box-shadow: 0 0 0 1px rgba(0, 192, 255, 0.5) inset !important;
}

:deep(.datav-switch.is-checked .el-switch__core) {
  background-color: rgba(0, 192, 255, 0.7) !important;
  border-color: rgba(0, 192, 255, 0.9) !important;
}

:deep(.datav-switch .el-switch__core) {
  background-color: rgba(0, 30, 60, 0.6) !important;
  border-color: rgba(0, 192, 255, 0.3) !important;
}

:deep(.el-button.tech-button--primary) {
  background-color: rgba(0, 192, 255, 0.2) !important;
  border-color: rgba(0, 192, 255, 0.7) !important;
  color: #00c0ff !important;
}

:deep(.el-button.tech-button--primary:hover) {
  background-color: rgba(0, 192, 255, 0.4) !important;
  border-color: #00c0ff !important;
  color: #ffffff !important;
  box-shadow: 0 0 10px rgba(0, 192, 255, 0.5) !important;
}

:deep(.el-button.tech-button) {
  background-color: rgba(0, 30, 60, 0.6) !important;
  border-color: rgba(0, 192, 255, 0.3) !important;
  color: rgba(0, 192, 255, 0.8) !important;
}

:deep(.el-button.tech-button:hover) {
  background-color: rgba(0, 30, 60, 0.8) !important;
  border-color: rgba(0, 192, 255, 0.7) !important;
  color: #ffffff !important;
}

.mx-1 {
  margin-left: 4px;
  margin-right: 4px;
}

.ml-1 {
  margin-left: 4px;
}

.w-20 {
  width: 100px;
}
</style>